/**
 * 
 */
jQuery(function($){
	
	var plan_grid="#plan-grid";
	var plan_pager="#plan-pager";
	var parent_volumn1=$(plan_grid).closest('[class*="col-"]');

	//resize the page size
	$(window).on('resize.jqGrid',function(){
		$(plan_grid).jqGrid('setGridWidth',parent_volumn1.width());
	})
	
	//resize on sidebar collapse/expand
	$(document).on('settings.ace.jqGrid',function(ev,event_name,collapsed){
		if(event_name==='sidebar_collapsed' || event_name==="main_container_fixed"){
			setTimeout(function(){
				$(plan_grid).jqGrid('setGridWidth',parent_volumn1.width());
				$(record_grid).jqGrid('setGridWidth',parent_volumn2.width());
				$(remind_grid).jqGrid('setGridWidth',parent_volumn3.width());
			},0);
		}
	});
	
	//create a jgGrid for plan_grid
	$(plan_grid).jqGrid({
		url:"loadSecurityUser", 
		datatype:"json",
		height:358,
		colNames:['ID','登录名','公司','联系方式','邮箱','真实姓名','角色权限','创建时间','关键字'],
		colModel:[
		          	{name:'id',index:'id',editable:true,search:false},
		          	{name:'username',index:'username',editable: false,search:false},
		          	{name:'comp',index:'comp',editable: true,search:false},
					{name:'phone',index:'phone',editable: true,search:false},
					{name:'email',index:'email',editable: true,search:false},
					{name:'realname',index:'realname',editable: true,search:false},
					{name:'role',index:'role',editable: false,search:false,edittype:"select",editoptions:{value:getRole()}},
					{name:'createTime',index:'createTime',editable: false,search:false},
					{name:'keywords',index:'keywords',editable:false,search:true,hidden:true,searchoptions:{searchhidden:true,sopt:['eq']}}
					
				], 
				
				viewrecords:true,//显示总记录
				rowNum:10,//每页记录数
				rowList:[10,20,30],//每页记录数选项
				pager:plan_pager,//设置pager栏的
				altRows:true,//设置zebra-striped的值,是否显示条纹线
				multiselect:true,//允许多选
				multiboxonly:true,//在允许multiselect下,允许checkbox
				loadComplete:function(){    //加载完成后执行的
					var table=this;         //plan-grid
					setTimeout(function(){
					//	styleCheckbox(table);//修改checkbox样式;
					//	updateActionIcon(table);//修改按钮样式;
						updatePagerIcons(table);//
					//	enableTooltips(table);//这些都是修改样式的代码,都是自定义的函数,在后面自己选择样式
					},0);
				},
				
				editurl: "securityUserEdit",//编辑时处理提交的url
				caption:"用户管理" //标题
				
	});
	
	$(window).triggerHandler('resize.jqGrid');//执行前面的方法,设置grid宽度
	
	
	//时间的设置,调用datepicker插件
	function pickDate(cellvalue,option,cell){
		setTimeout(function(){
			$(cell).find('input[type=text]').datepicker({format:'yyyy-mm-dd HH:MM:ss',autoclose:true});
		},0);
	}
	
	function getRole(){
		var str="";
		$.ajax({
			type:"post",
			async:false,
			url:"loadSecurityRoleSelect",
			success:function(data){
				for(var i=0;i<data.length;i++){
					if(i!=data.length-1){
						str+=data[i].id+":"+data[i].description+";";
					}else{
						str+=data[i].id+":"+data[i].description;
					}
				}
			}
		});
		return str;
	}
	
	//以下内容是配置plan-pager控制栏的
	$(plan_grid).jqGrid('navGrid',plan_pager,{
		//pager控制栏要有以下功能
		edit:true,
		editicon : 'ace-icon fa fa-pencil blue',
		add: false,
		addicon : 'ace-icon fa fa-plus-circle purple',
		del: true,
		delicon : 'ace-icon fa fa-trash-o red',
		search: true,
		searchicon : 'ace-icon fa fa-search orange',
		refresh: true,
		refreshicon : 'ace-icon fa fa-refresh green',
		view: true,
		viewicon : 'ace-icon fa fa-search-plus grey',
	},
	{
		//edit编辑栏点击执行的内容
		drag:false,
		closeAfterEdit:true,
		recreateForm: true,
		//显示编辑栏dialog前
		beforeShowForm:function(e){
			var form = $(e[0]);
			form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header"></div>')//包裹样式
			style_edit_form(form);//修改编辑栏样式
			enabledrag(form);
		}
	},
	{
		//add添加纪录点击执行内容
		drag:false,
		closeAfterAdd:true,
		recreatForm:true,
		clearAfterAdd : true,
		viewPagerButton:false,
		beforeShowForm:function(e){
			var form=$(e[0]);
			form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header"></div>');
			style_edit_form(form);
			enabledrag(form);
		}
	},
	{
		//delete删除记录执行
		drag:false,
		recreateForm:true,
		beforeShowForm:function(e){
			var form=$(e[0]);
//			console.log(form.data('styled'));
			if(form.data('styled')){
				return false;
			}
			form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header"></div>');
			style_delete_form(form);
			form.data('styled',true);
			enabledrag(form);
		},
		onclick:function(e){
			
		}
	},
	{
		//search 查找记录执行
		drag:false,
		recreatrForm:true,
		afterShowSearch:function(e){
			var form=$(e[0]);
			form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-headder"></div>')
			style_search_form(form);
			enabledrag(form);
		},
		afterRedraw:function(){
			style_search_filters($(this));
		},
		multipleSearch:false
	},
	{
		//view查看记录执行
		drag:false,
		recreateForm:true,
		beforeShowForm:function(e){
			var form=$(e[0]);
			enabledrag(form);
			form.closest('.ui-jqdialog').find('ui-jqdialog-title').wrap('<div class="widget-header"></div>')
		}
	}).navButtonAdd(plan_pager,{
		caption:"",
		title:"修改密码",
		buttonicon:"ui-icon ace-icon fa fa-check",
		onClickButton:function(){
			if($("#dialog-edit")){
				$("#dialog-edit").remove();
			}
			var id=$(plan_grid).getGridParam('selrow');
			var rowData = $(plan_grid).getRowData(id);
			
			 $.ajax({
     			type:"post",
     			async:false,
     			url:"loadSecurityRoleSelect",
     			success:function(data){
					$("body").append('<div class="hide" id="dialog-edit"></div>');
	                $("#dialog-edit").append('<div class="widget-body edit-body"></div>');
	                    $(".edit-body").append('<div class="widget-main no-padding edit-main"></div>');
	                    $(".edit-main").append('<div class="col-xs-12" style="margin-top:5px;"><label class="col-xs-4" style="margin-top:3px;">密码：</label><input type="text" id="eplainPassword" class="col-xs-8"></div>');
     			}
			 });
		    
		    $( "#dialog-edit" ).removeClass('hide').dialog({
				resizable: false,
				modal: true,
				title: "修改密码",
				buttons: [
					{
						html: "<i class='ace-icon fa fa-trash-o bigger-110'></i>&nbsp; 执行",
						"class" : "btn btn-danger btn-minier",
						click: function() {
							$( this ).dialog( "close" );
							$.ajax({
								url:"updateSecurityUserPassword",
								data:{id:id,plainPassword:$("#eplainPassword").val()},
								success:function(){
									jQuery("#plan-grid").jqGrid('setGridParam', {
						                
						            }).trigger('reloadGrid');
								}
							})
						}
					}
					,
					{
						html: "<i class='ace-icon fa fa-times bigger-110'></i>&nbsp; 取消",
						"class" : "btn btn-minier",
						click: function() {
							$( this ).dialog( "close" );
						}
					}
				]
			});
		},
		position:"first"
	}).navButtonAdd(plan_pager,{
		caption:"",
		title:"添加",
		buttonicon:"ace-icon fa fa-plus-circle purple",
		onClickButton:function(){
			if($("#dialog-add")){
				$("#dialog-add").remove();
			}
	                    
	                    $.ajax({
	            			type:"post",
	            			async:false,
	            			url:"loadSecurityRoleSelect",
	            			success:function(data){
	            				$("body").append('<div class="hide" id="dialog-add"></div>');
	        	                $("#dialog-add").append('<div class="widget-body add-body"></div>');
	        	                    $(".add-body").append('<div class="widget-main no-padding add-main"></div>');
	        	                    $(".add-main").append('<div class="col-xs-12"><label class="col-xs-4" style="margin-top:3px;">登录名：</label><input type="text" id="username" class="col-xs-8"></div>');
	        	                    $(".add-main").append('<div class="col-xs-12" style="margin-top:5px;"><label class="col-xs-4" style="margin-top:3px;">密码：</label><input type="text" id="plainPassword" class="col-xs-8"></div>');
	        	                    $(".add-main").append('<div class="col-xs-12" style="margin-top:5px;"><label class="col-xs-4" style="margin-top:3px;">公司：</label><input type="text" id="comp" class="col-xs-8"></div>');
	        	                    $(".add-main").append('<div class="col-xs-12" style="margin-top:5px;"><label class="col-xs-4" style="margin-top:3px;">电话：</label><input type="text" id="phone" class="col-xs-8"></div>');
	        	                    $(".add-main").append('<div class="col-xs-12" style="margin-top:5px;"><label class="col-xs-4" style="margin-top:3px;">邮箱：</label><input type="text" id="email" class="col-xs-8"></div>');
	        	                    $(".add-main").append('<div class="col-xs-12" style="margin-top:5px;"><label class="col-xs-5" style="margin-top:3px;">真实姓名：</label><input type="text" id="realname" class="col-xs-7"></div>');
	        	                    $(".add-main").append('<div class="col-xs-12" style="margin-top:5px;"><label class="col-xs-4">角色权限</label>\
	    		                    		<select id="role" class="col-xs-8">');
	        	                    $("#role").append('<option value="0">请选择</option>');
	            				for(var i=0;i<data.length;i++){
	            					$("#role").append('<option value='+data[i].id+'>'+data[i].description+'</option>');
	            				}
	            				 $(".add-main").append('<div>');
	            			}
	            		});
		    
		    $( "#dialog-add" ).removeClass('hide').dialog({
				resizable: false,
				modal: true,
				title: "添加",
				buttons: [
					{
						html: "<i class='ace-icon fa fa-trash-o bigger-110'></i>&nbsp; 执行",
						"class" : "btn btn-danger btn-minier",
						click: function() {
							$( this ).dialog( "close" );
							$.ajax({
								url:"addSecurityUser",
								data:{username:$("#username").val(),plainPassword:$("#plainPassword").val(),phone:$("#phone").val(),email:$("#email").val(),realname:encodeURI($("#realname").val()),role:$("#role").val(),comp:encodeURI($("#comp").val())},
								success:function(){
									jQuery("#plan-grid").jqGrid('setGridParam', {
						                
						            }).trigger('reloadGrid');
								}
							})
						}
					}
					,
					{
						html: "<i class='ace-icon fa fa-times bigger-110'></i>&nbsp; 取消",
						"class" : "btn btn-minier",
						click: function() {
							$( this ).dialog( "close" );
						}
					}
				]
			});
		},
		position:"first"
	});
	//样式修改
	function style_edit_form(form){
		//添加datapicker选项功能
		form.find('input[name=startTime]').datepicker({format:'yyyy-mm-dd' , autoclose:true});
		form.find('input[name=lastTime]').datepicker({format:'yyyy-mm-dd' , autoclose:true});
		form.find('input[name=nextTime]').datepicker({format:'yyyy-mm-dd' , autoclose:true});
		form.find('input[name=endTime]').datepicker({format:'yyyy-mm-dd' , autoclose:true});
	}
	function style_delete_form(form){
		
	}
	function style_search_filters(form){
		form.find('.delete-rule').val('X');
		form.find('.add-rule').addClass('btn btn-xs btn-primary');
		form.find('.add-group').addClass('btn btn-xs btn-success');
		form.find('.delete-group').addClass('btn btn-xs btn-danger');
	}
	function style_search_form(form){
		var dialog = form.closest('.ui-jqdialog');
		var buttons = dialog.find('.EditTable')
		buttons.find('.EditButton a[id*="_reset"]').addClass('btn btn-sm btn-info').find('.ui-icon').attr('class', 'ace-icon fa fa-retweet');
		buttons.find('.EditButton a[id*="_query"]').addClass('btn btn-sm btn-inverse').find('.ui-icon').attr('class', 'ace-icon fa fa-comment-o');
		buttons.find('.EditButton a[id*="_search"]').addClass('btn btn-sm btn-purple').find('.ui-icon').attr('class', 'ace-icon fa fa-search');
	}
	function beforeDeleteCallback(e){
		
	}
	function beforeEditCallback(e){
		
	}
	function styleCheckbox(table){
		
	}
	function updateActionIcon(table){
		
	}
	function updatePagerIcons(table){
		var replacement = 
		{
			'ui-icon-seek-first' : 'ace-icon fa fa-angle-double-left bigger-140',
			'ui-icon-seek-prev' : 'ace-icon fa fa-angle-left bigger-140',
			'ui-icon-seek-next' : 'ace-icon fa fa-angle-right bigger-140',
			'ui-icon-seek-end' : 'ace-icon fa fa-angle-double-right bigger-140'
		};
		$('.ui-pg-table:not(.navtable) > tbody > tr > .ui-pg-button > .ui-icon').each(function(){
			var icon = $(this);
			var $class = $.trim(icon.attr('class').replace('ui-icon', ''));
			
			if($class in replacement) icon.attr('class', 'ui-icon '+replacement[$class]);
		});
		
	}
	function enableTooltips(table){
		$('.navtable .ui-pg-button').tooltip({container:'body'});
		$(table).find('.ui-pg-div').tooltip({container:'body'});
	}
	$(document).on('ajaxloadstart.page',function(e){
		$.jgrid.gridDestroy(grid_selector);
		$('.ui-jqdialog').remove();
	});
	function enabledrag(form){
		var dialog=form.closest('.ui-jqdialog');
		dialog.css('left',600).draggable();
	}
	
})